package com.beta.backend.gateway.filter;

import com.beta.cat.service.RedissonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @description 开发者授权（针对服务端、接口）
 * @author: zdwang
 * @date 2021/12/2 15:00
 */
@Slf4j
@Component
public class DeveloperAuthGatewayFilter extends AbstractGatewayFilter implements GatewayFilter, Ordered {

    @Autowired
    private RedissonService redissonService;

    private static final String TOKEN = "token";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest().mutate().build();
        // 获取请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        // 判断参数中是否含有token
        if (!queryParams.containsKey(TOKEN)){
            return unauthorized(exchange);
        }

        // 判断token是否过期
        String token = queryParams.getFirst(TOKEN);
        String corpId = redissonService.get(token);

        if (StringUtils.isEmpty(corpId)){
            log.warn("从缓存获取 corpId 为空，token = {}", token);
            return unauthorized(exchange);
        }

        return chain.filter(exchange.mutate().request(request).build());
    }


    @Override
    public int getOrder() {
        return 13;
    }
}
